package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DouYinOrderCheckTask {


    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;

    private Log logger = Log.get();


    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate = 5000)
    public void checkOrder() throws Exception {
//        logger.info("乐刷订单查询..");
        Calendar c = Calendar.getInstance();
        TOrderInfo query = new TOrderInfo();
        query.setChannelType("alipay");
        query.setChannel("alipay_dy_h5");
        query.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(query);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date startTime = DateUtils.getStartOfDay(new Date());
        Date endTime = DateUtils.getEndOfDay(new Date());
        String startTimeStr = sdf.format(startTime);
        String endTimeStr = sdf.format(endTime);
        for (TOrderInfo orderInfo : orderInfos) {
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
            TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String url = "https://tp-pay.snssdk.com/gateway-cashier2/tp/cashier/trade_query";
            String cookieStr = orderInfo.getQrcodeTxt();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            HashMap<String, String> headerMap = new HashMap();
            JSONObject riskInfoObj = new JSONObject();
            riskInfoObj.put("device_platform", "iphone");
            JSONObject bizContentObj = new JSONObject();
            bizContentObj.put("trade_no", cookieObj.getString("trade_no"));
            String biz_content = "scene=h5&risk_info=" + URLEncoder.encode(riskInfoObj.toString()) + "&biz_content="+URLEncoder.encode(bizContentObj.toString()) +"&process=" + URLEncoder.encode(cookieObj.getString("process"));
//            logger.info("订单查询请求："+biz_content);
//            HttpResponse httpResponse = HttpUtils.httpFormPost(url, headerMap, "", queryObj, "好多分订单查询", "");
            String paytypeInfo = HttpUtils.sendPostRequest(url, biz_content, headerMap);
            JSONObject resultObj = JSONObject.parseObject(paytypeInfo);
//            logger.info("抖音订单查询.."+resultObj);
            String resultCode = resultObj.getString("code");
            if (resultCode.equalsIgnoreCase("CA0000")) {
                JSONObject tradeInfo = resultObj.getJSONObject("data").getJSONObject("trade_info");
                if (tradeInfo.getString("status").equalsIgnoreCase("success")) {
                    logger.info("抖音订单查询.." + tradeInfo);
                    MsgPayResult msgPayResult = new MsgPayResult();
                    msgPayResult.setChannel(orderInfo.getChannel());
                    msgPayResult.setTradeNo(orderInfo.getId().toString());
                    msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                    msgPayResult.setOrderId(tradeInfo.getString("out_trade_no"));
                    msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                    msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                    msgPayResult.setBillTime(timeStamp2Date(tradeInfo.getString("pay_time")));

                    msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(tradeInfo));
                    chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                    chargeService.notifyUserPaySucc(orderInfo.getId());

                    logger.info("抖音订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney());
                }

            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }

    private String getParamByUrl(String url, String name) {
        url += "&";
        String pattern = "(\\?|&){1}#{0,1}" + name + "=[a-zA-Z0-9]*(&{1})";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(url);
        if (m.find()) {
            return m.group(0).split("=")[1].replace("&", "");
        } else {
            return null;
        }
    }
}
